import datetime

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from .Ser import *
# Create your views here.
from .db import Dd


class User_M(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        data = User.objects.filter(username=username).first()
        if data and (data.password, password):
            return Response({'code': 200, 'msg': '登录成功'})
        else:
            return Response({'code': 10010, 'msg': '登录失败'})


class Youhui_M(APIView):
    def post(self, request):
        data = Youhui_Ser(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'code': 200, 'msg': '添加成功'})
        else:
            return Response({'code': 10010, 'msg': '添加失败'})

    def get(self, request):
        data = Youhui.objects.all()
        all = Youhui_Ser(data, many=True)
        return Response(all.data)


import uuid


class UserYouhui_M(APIView):
    def post(self, request):
        user = request.data.get('user')
        youhui = request.data.get('youhui')
        print(user)
        print(youhui)
        uuids = str(uuid.uuid1())
        nudata = UserYouhui.objects.filter(user=user, youhui=youhui).first()
        print(222)
        if nudata:
            return Response({'code': 10010, 'msg': '已领取'})
        datas = Youhui.objects.filter(id=youhui).first()
        print(datas.price)
        print(333)
        data1 = {'user': user,
                 'youhui': youhui,
                 'uuid': uuids,
                 'start_time': datas.start_time,
                 'end_time': datas.end_time,
                 'price': datas.price,
                 'name': datas.name}
        all = UserYous_Ser(data=data1)
        if all.is_valid():
            datas.count -= 1
            datas.save()
            all.save()
            return Response({'code': 100103})
        else:
            print(all.errors)
            return Response({'code': 500})

    def get(self, request):
        user = request.GET.get('user')
        print(user)
        price = request.GET.get('price')
        print(price)
        datetimes = datetime.datetime.now()
        print(datetimes)
        data = UserYouhui.objects.filter(user=user, price__lt=price, start_time__lt=datetimes,
                                         end_time__gt=datetimes).all()
        all = UserYouhui_Ser(data, many=True)
        return Response({'code': '200', 'list': all.data})




from dwebsocket.decorators import accept_websocket
from django.http import HttpResponse, JsonResponse
import json

# 存储连接websocket的用户
clients = {}


@accept_websocket
def websocketLink(request,id):
    # 获取连接
    if request.is_websocket:
        # 新增 用户  连接信息
        clients[id] = request.websocket
        # 监听接收客户端发送的消息 或者 客户端断开连接
        for message in request.websocket:
            break


# 发送消息
def websocketMsg(client, msg):
    b1 = json.dumps(msg, ensure_ascii=False).encode('utf-8')
    client.send(b1)


# 服务端发送消息
def send(request,id):
    # if clients:
    #     for i in clients:
    websocketMsg(clients[id], {'title': '您有新的订单了','id':id})
    return HttpResponse("ok")
import time
import redis


# class GET_get(APIView):
def get_dese(request):
    db = Dd()
    res = db.get_all(
        "select customer.name,customer.tmoney,customer.compay_name,customer.state,customer.id,customer_manager.name as se from customer inner join reg_form on customer.reformid=reg_form.id inner join customer_manager on customer_manager.id=customer.manager_id")

    return JsonResponse({'code': '200', 'list': res})


def post_subimet(request):
    data = request.POST
    print(data)
    db = Dd()
    # 修改状态
    db.update(
        "update customer set state = %s,audit_time=%s,audit_name='zs' where id=%s" % (
        data['radio'], int(time.time()), data['id']))
    if int(data['radio']) == 2:
        # 查询相对应的服务 提交审核
        res = db.get_one("select * from customer where id=%s" % (data['id']))
        # 修改审核机构数量
        db.update("update reg_form set tcount=tcount+1 where id=%s" % res['reformid'])
        # 修改客户经理金额
        db.update("update customer_manager set tmoney=tmoney+%s where id=%s" % (res['tmoney'], res['manager_id']))
        # manager_id
    return JsonResponse({'code': '200'})


